import { constantRoutes } from '@/router'
import { getRoutersApi } from '@/api/menu'
import { toTreeByRecursion } from '@/utils'
import Layout from '@/layout'
import ParentView from '@/components/ParentView'

const roleList = [
  'system',
  'project',
  'system:user',
  'system:user:add',
  'system:role',
  'system:menu',
  'system:dept',
  'system:post',
  'project:list',
  'project:archived-project-list'
]

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  async generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      getRoutersApi({}).then((res) => {
        if (res && res.code === 0) {
          let routers = res.data
          routers = routers.map((route) => {
            const obj = {
              menu_id: route.menu_id,
              parent_id: route.parent_id,
              path: route.path,
              component: route.component,
              hidden: Boolean(+route.visible),
              meta: {
                menu_type: route.menu_type,
                title: route.menu_name,
                icon: '',
                roles: route.perms, // you can set roles in root nav
                is_frame: !+route.is_frame
              }
            }

            return obj
          })
          routers = toTreeByRecursion(routers, 'menu_id', 'parent_id', 0, 'children')
          routers = filterAsyncRoutes(routers, roleList)
          routers = loadAsyncTreeRoutes(routers, false)

          commit('SET_ROUTES', routers)
          resolve(routers)
        }
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

function loadAsyncTreeRoutes(routes, isInner = false) {
  return routes.map((route) => {
    if (route.children) {
      route.children = loadAsyncTreeRoutes(route.children, true)
    }

    if (!route.meta.is_frame) {
      if (route.meta.menu_type === 'M' && !isInner) {
        route.component = Layout
        console.log(Layout)
      } else if (route.meta.menu_type === 'M' && isInner) {
        route.component = ParentView
      } else {
        route.component = loadView(route.component)
      }
    }

    delete route.menu_id
    delete route.parent_id

    return route
  })

  // childrenMap.forEach((el, index) => {
  //   if (el.menu_type === 'M' && !isInner) {
  //     el.component = Layout
  //   } else if (el.menu_type === 'M' && isInner) {
  //     el.component = ParentView
  //   }
  // })
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}
